<template>
  <view class="page page-activity-form ui-form-basic">
    <fui-form ref="formRef" :model="form" class="form-wrapper grey" labelWidth="200" labelSize="28" labelWeight="bold">
      <view class="form-block-title">基本信息</view>
      <view class="form-block">
        <fui-form-item :bottomBorder="false" label="活动封面" prop="cover" :padding="['16rpx', 0]">
          <template #vertical>
            <upload-image class="form-upload" @uploaded="uploadedCover" :defaultList="form.cover ? [form.cover] : []"></upload-image>
          </template>
        </fui-form-item>
        <fui-form-item label="活动名称" prop="name" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-input size="28" maxlength="20" :padding="[0]" :borderBottom="false" placeholder="请输入活动名称" v-model="form.name"></fui-input>
        </fui-form-item>
        <fui-form-item label="活动开始时间" prop="startTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('startTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择活动开始时间" v-model="form.startTimeText" disabled></fui-input>
        </fui-form-item>
        <fui-form-item label="活动结束时间" prop="endTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('endTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择活动结束时间" v-model="form.endTimeText" disabled></fui-input>
        </fui-form-item>
        <!-- <fui-form-item label="活动描述" prop="description" left="0" marginTop="14" :padding="['16rpx', 0]">
          <template v-slot:vertical>
            <fui-textarea size="28" maxlength="500" height="64rpx" :isCounter="true" radius="16" borderColor="#DFDFDF" v-model="form.description" placeholder="请输入活动描述" textareaBorder></fui-textarea>
          </template>
        </fui-form-item> -->
      </view>
      <view class="form-block-title">优惠设置</view>
      <view class="form-block">
        <fui-form-item :bottomBorder="false" label="优惠类型" prop="discountType"
          labelWeight="600" :left="0" labelWidth="200" class="textarea-box" labelSize="28">
          <view class="cycle-box">
            <view class="cycle" :class="{'cycle-active': form.discountType == item.code}"
              v-for="item in ACTIVITY_DISCOUNT_TYPE" :key="item.code" @click="handleChangeDiscountType(item.code)">
              <image v-if="form.discountType == item.code" class="cycleimg"
                src="../../../static/images/cycleimg.png" mode=""></image>
              {{item.name}}
            </view>
          </view>
        </fui-form-item>
        <view class="form-block-title">满减门槛及优惠<fui-text :text="`(${discountList.length}/5)`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text></view>
        <view class="discount-list">
          <view class="discount-item" :class="{'is-shake': showError && item.validType}" v-for="(item, index) in discountList" :key="index">
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].aLabel" size="24"></fui-text>
            <fui-form-item label="" prop="startNum" left="0" :padding="['16rpx', 0]">
              <fui-input v-model="item.startNum" type="number" placeholder="满减门槛" backgroundColor="transparent" size="24" :padding="[0]" :borderBottom="false" :maxlength="20" @input="onChangeStartNum($event, index)"></fui-input>
            </fui-form-item>
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].aUnit" size="24"></fui-text>
            <fui-text text="，" size="24"></fui-text>
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].bLabel" size="24"></fui-text>
            <fui-form-item label="" prop="discountNum" left="0" :padding="['16rpx', 0]">
              <fui-input v-model="item.discountNum" type="digit" placeholder="优惠力度" backgroundColor="transparent" size="24" :padding="[0]" :borderBottom="false" :maxlength="20" @input="onChangeDiscountNum($event, index)"></fui-input>
            </fui-form-item>
            <fui-text :text="ACTIVITY_DISCOUNT_TYPE[form.discountType].bUnit" size="24"></fui-text>
            <fui-icon v-if="index === 0" name="plussign-fill" size="40" color="#f95a5a" @click="handleAddDiscount"></fui-icon>
            <fui-icon v-else name="minussign-fill" size="40" color="var(--fui-color-primary)" @click="handleRemoveDiscount(index)"></fui-icon>
          </view>
        </view>
        <fui-form-item :bottomBorder="false" label="商品范围" prop="productScope"
          labelWeight="600" :left="0" labelWidth="200" class="textarea-box" labelSize="28">
          <view class="cycle-box">
            <view class="cycle" :class="{'cycle-active': form.productScope == item.code}"
              v-for="item in ACTIVITY_GOODS_RANGE" :key="item.code" @click="handleChangeGoodsRange(item.code)">
              <image v-if="form.productScope == item.code" class="cycleimg"
                src="../../../static/images/cycleimg.png" mode=""></image>
              {{item.name}}
            </view>
          </view>
          <fui-text text="活动创建后，商品范围将无法修改。" :padding="['16rpx', 0]" size="24" color="#999"></fui-text>
        </fui-form-item>
        <view class="form-block-title" v-if="form.productScope === 32">
          已选商品<fui-text :text="`(${goodsList.length})`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <view class="form-block-tools">
            <fui-text :text="goodsList.length ? '管理商品' : '添加商品'" size="24" color="var(--fui-color-primary)" @click="handleManageGoods"></fui-text>
          </view>
        </view>
      </view>
    </fui-form>

    <view class="btn-wrapper ui-fixed-footer">
      <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="tab.navigateBack"></fui-button>
      <fui-button text="保存" height="78rpx" radius="8rpx" :margin="['0']" @click="handleSubmit"></fui-button>
    </view>

    <fui-date-picker :show="onShowDatePicker" type="5" :value="defaultDateTime" @change="onChangeDate" @cancel="onCancelDate"></fui-date-picker>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { setTitle } from '@/utils/common'
import utils from '@/components/firstui/fui-utils'
import { ACTIVITY_DISCOUNT_TYPE, ACTIVITY_GOODS_RANGE, ACTIVITY_VALID_MESSAGE } from './consts'
import uploadImage from '@/components/upload/image'
import activityApi from '@/api/activity/supplier'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const activityId = ref('')
onLoad((option) => {
  if (option.activityId) {
    setTitle('编辑活动')
    activityId.value = option.activityId
    getActivityDetail()
  }
})

const formRef = ref(null)
const form = ref({
  discountType: 21
})
const rules = [
  {
    name: 'cover',
    rule: ['required'],
    msg: ['请上传活动封面']
  },
  {
    name: 'name',
    rule: ['required'],
    msg: ['请输入活动名称']
  },
  {
    name: 'startTimeText',
    rule: ['required'],
    msg: ['请选择活动开始时间']
  },
  {
    name: 'endTimeText',
    rule: ['required'],
    msg: ['请选择活动结束时间']
  },
  {
    name: 'productScope',
    rule: ['required'],
    msg: ['请选择商品范围']
  }
]

const uploadedCover = (e) => {
  form.value.cover = e[0]
}
const handleChangeDiscountType = (code) => {
  if (activityId.value) {
    modal.msgError('优惠类型不允许修改！')
    return
  }
  form.value.discountType = code
  discountList.value = [{}]
}
const handleChangeGoodsRange = async (productScope) => {
  if (activityId.value) {
    modal.msgError('商品范围不允许修改！')
    return
  }
  try {
    const res = await activityApi.checkGoodsRange({
      productScope,
      supplierId: store.getters.companyId
    })
    if (res.code === 0) {
      form.value.productScope = productScope
      goodsList.value = []
      store.commit('SET_ACTIVITY_GOODS', [])
    } else {
      modal.msgError(res.msg || '商品范围校验出错！')
    }
  } catch (err) {
    modal.msgError(err.msg || '商品范围校验出错！')
  }
}

// 活动时间
const defaultDateTime = utils.dateFormatter(new Date(), 'y-m-d h:i', 4)
const onShowDatePicker = ref(false)
const curDateFiled = ref('')
const handleShowDatePicker = (field) => {
  curDateFiled.value = field
  onShowDatePicker.value = true
}
const onChangeDate = (e) => {
  form.value[curDateFiled.value] = e ? `${e.year}/${e.month}/${e.day} ${e.hour}:${e.minute}` : ''
  onShowDatePicker.value = false
}
const onCancelDate = () => {
  onShowDatePicker.value = false
}

// 指定商品
const goodsList = ref([])
const handleManageGoods = () => {
  tab.navigateTo(`/pages/activity/supplier/${goodsList.value.length ? 'goods' : 'selectGoods'}?activityId=${activityId.value}&isForm=1`)
}
onShow(() => {
  if (activityId.value) {
    getGoodsList()
  } else {
    goodsList.value = store.getters.activityGoods
  }
})
onBackPress(() => {
  store.commit('SET_ACTIVITY_GOODS', [])
})

// 满减门槛及优惠设置
const discountList = ref([{}])
const onChangeStartNum = async (value, index) => {
  if (value <= 0) {
    modal.msgError('满减门槛必须大于0！')
    discountList.value[index].startNum = await ''
  } else if (value.toString().indexOf('.') > -1) {
    modal.msgError('满减门槛必须为整数！')
    discountList.value[index].startNum = await ''
  }
  showError.value = false
}
const onChangeDiscountNum = async (value, index) => {
  if (value <= 0) {
    modal.msgError('优惠力度必须大于0！')
    discountList.value[index].discountNum = await ''
  } else if (form.value.discountType === 21 && value.toString().indexOf('.') > -1) {
    modal.msgError('优惠力度必须为整数！')
    discountList.value[index].discountNum = await ''
  } else if (form.value.discountType === 22 && value >= 10) {
    modal.msgError('优惠力度必须小于10！')
    discountList.value[index].discountNum = await ''
  } else if (form.value.discountType === 22 && value.toString().indexOf('.') > -1 && value.toString().split('.')[1].length > 1) {
    modal.msgError('优惠力度必须精确到1位小数！')
    discountList.value[index].discountNum = await ''
  }
  showError.value = false
}
const handleAddDiscount = () => {
  if (discountList.value.length >= 5) {
    modal.msgError('优惠力度最多支持添加5个！')
    return
  }
  discountList.value.push({})
}
const handleRemoveDiscount = (index) => {
  discountList.value.splice(index, 1)
}

// 校验满减门槛及优惠设置
const showError = ref(false)
const isNoValidDiscount = (row) => {
  let validType = ''
  if (!row.startNum || !row.discountNum) {
    validType = 'empty'
  } else if (form.value.discountType === 21 && (row.startNum - row.discountNum <= 0)) {
    validType = 'above'
  }
  return validType
}
const validatorDiscountList = () => {
  let isValid = true
  discountList.value.forEach(item => {
    item.validType = isNoValidDiscount(item)
    if (item.validType) {
      showError.value = true
      isValid = false
      modal.msgError(ACTIVITY_VALID_MESSAGE[item.validType])
      return
    } else {
      showError.value = false
      isValid = true
    }
  })
  return isValid
}

// 活动详情
const getActivityDetail = () => {
  modal.loading('加载中...')
  try{
    activityApi.getActivityDetail(activityId.value).then(res => {
      modal.closeLoading()
      if (res.code === 0 && res.data) {
        form.value = res.data
        form.value.startTimeText = utils.dateFormatter(new Date(res.data.startTime), 'y/m/d h:i', 4)
        form.value.endTimeText = utils.dateFormatter(new Date(res.data.endTime), 'y/m/d h:i', 4)
        const resList = res.data.discountRules.split(',')
        const list = resList.map(item => {
          return {
            startNum: item.split('-')[0],
            discountNum: item.split('-')[1]
          }
        })
        discountList.value = list
        store.commit('SET_ACTIVITY_GOODS', goodsList.value)
      } else {
        modal.msgError(res.msg)
      }
    })
  }catch(err){
    modal.closeLoading()
    modal.msgError(err)
  }
}

// 获取活动商品
const getGoodsList = () => {
  try{
    activityApi.getCheckedGoodsList(activityId.value).then((res) => {
      if(res.code === 0){
        goodsList.value = (res.data || []).map((item) => {
          return {
            ...item,
            imgUrl: item.sliderPicUrls ? item.sliderPicUrls[0] : JSON.parse(item.picUrl)[0]
          }
        })
        store.commit('SET_ACTIVITY_GOODS', goodsList.value)
      }else{
        modal.msgError(res.msg)
      }
    })
  }catch(err){
    modal.msgError(err)
  }
}

// 提交表单方法
const handleSubmit = async () => {
  const validRes = await formRef.value.validator(form.value, rules)
  if (validRes.isPassed) {
    const startTime = new Date(form.value.startTimeText).getTime()
    const endTime = new Date(form.value.endTimeText).getTime()
    if (endTime <= startTime) {
      modal.msgError('活动结束时间必须大于活动开始时间！')
      return
    }
    const validList = validatorDiscountList()
    if (!validList) {
      return
    }
    if (form.value.productScope === 32 && !goodsList.value.length) {
      modal.msgError('请至少添加一个活动商品！')
      return
    }
    const discountRules = discountList.value.map(item => item.startNum + '-' + item.discountNum)
    const productSpuIds = goodsList.value.map(item => item.id)
    const formData = {
      ...form.value,
      supplierId: store.getters.companyId,
      startTime,
      endTime,
      discountRules: discountRules.join(','),
      productSpuIds: productSpuIds.join(',')
    }
    const apiUrl = form.value.id ? 'updateActivity' : 'addActivity'
    activityApi[apiUrl](formData).then((res) => {
      store.commit('SET_ACTIVITY_GOODS', [])
      if (res.code === 0) {
        modal.msg(`活动信息已${form.value.id ? '修改' : '添加'}！`)
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msgError(res.msg)
      }
    })
  }
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.page-activity-form {
  padding-bottom: 150rpx;

  .discount-list {
    .discount-item {
      display: flex;
      align-items: center;
      margin-top: 32rpx;
      padding: 0 10rpx;
      &.is-shake {
        border: 2rpx dashed #f95a5a;
      }
      ::v-deep .fui-text__wrap {
        .fui-text__content {
          white-space: nowrap;
        }
      }
      .fui-form__item-wrap {
        width: auto;
        border-radius: 8rpx !important;
        background-color: #f7f7f7 !important;
        margin: 0 10rpx;
        padding: 0 16rpx;
      }
      .fui-icon {
        margin-left: 24rpx;
      }
    }
  }
  ::v-deep.textarea-box .fui-form__wrap-inner {
    display: initial !important;
    padding: 0 !important;
  }

  .cycle-box {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .cycle {
      width: 160rpx;
      height: 64rpx;
      background: #F5F7FE;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
      opacity: 1;
      border: 2rpx solid #E7EBFB;
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #333333;
      text-align: center;
      line-height: 64rpx;
      margin-right: 20rpx;
      position: relative;
    }

    .cycle-active {
      font-weight: bold;
      color: var(--fui-color-primary);
      border: 2rpx solid var(--fui-color-primary);
    }

    .cycleimg {
      width: 30rpx;
      height: 27rpx;
      display: block;
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>